// pages/address/add-address/add-address.js
//pages/address/add-address/add-address?addressInfo='xx'
//调用界面需实现onResultAddAddress(addressInfo)或onResultEditAddress(addressInfo)方法

var httpUtil = require('../../../utils/httpUtil.js')
var uiUtil = require('../../../utils/uiUtil.js')
var util = require('../../../utils/util.js')
var that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isAddAddress: true, //true:新增,false：编辑
    addressInfo: {},
    // userName:null,
    // phoneNo:null,
    // areaCode:null,
    // areaName:null,
    // adress:null,
    // isDefaultAddress:1,


    //地址选择器
    showLoadAddr: false, //true:地址列表正在加载中
    addrCurIndex: 0, //当前所在位置，0-3
    addrSelecteds: [], //已选择的区域
    addrDatas: [], //所有区域
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var addressInfo;
    try {
      addressInfo = JSON.parse(decodeURIComponent(options.addressInfo))
    } catch (e) {}

    if (addressInfo) {
      wx.setNavigationBarTitle({
        title: '修改收货地址',
      })
      this.setData({
        addressInfo: addressInfo,
        isAddAddress: false
      })
    } else {
      wx.setNavigationBarTitle({
        title: '新增收货地址',
      })

      this.setData({
        isAddAddress: true
      })
    }


    that = this;
  },
  onShareAppMessage: function (res) {
    return util.handleShareApp()
  },
  /**
   * 收货人输入
   */
  onUserNameInput(e) {
    this.setData({
      'addressInfo.userName': e.detail.value,
    })
  },
  /**
   * 手机号码输入
   */
  onPhoneNoInput(e) {
    this.setData({
      'addressInfo.phoneNo': e.detail.value,
    })
  },
  /**
   * 收货人输入
   */
  onAddressInput(e) {
    this.setData({
      'addressInfo.adress': e.detail.value,
    })
  },
  onDefaultClick(e) {
    var lastStatus = this.data.addressInfo.isDefaultAddress || 0
    lastStatus = lastStatus == 1 ? 0 : 1
    this.setData({
      'addressInfo.isDefaultAddress': lastStatus,
    })
  },
  /**
   * 地区选择点击
   */
  onAreaClick() {
    if (!this.data.addrDatas[0]) {
      this.addrChangeCurShow(0)
    }
    this.setData({
      showAddrView: true,
    })
  },

  /**
   * 保存按钮
   */
  onSaveBtnLick() {
    var params = this.data.addressInfo
    if (!params) {
      uiUtil.showToast("请填写地址信息")
      return;
    }
    if (!params.userName) {
      uiUtil.showToast("请填写收货人姓名")
      return;
    }

    if (!params.phoneNo) {
      uiUtil.showToast("请填写手机号码")
      return;
    }

    if (!params.areaCode) {
      uiUtil.showToast("请选择所在地区")
      return;
    }

    if (!params.adress) {
      uiUtil.showToast("请填写详细地址")
      return;
    }

    this.requestReplaceAddress(params)
  },


  /**
   * 已选择的地址标题点击事件
   */
  addrTitleClick(e) {
    if (this.data.showLoadAddr) { //正在加载中
      return;
    }
    var index = e.currentTarget.dataset.index
    this.addrChangeCurShow(index)
  },

  /**
   * 切换当前显示地区
   * index:第几个
   */
  addrChangeCurShow(index) {
    //检测是否需要网络加载
    try {
      if (that.data.addrDatas[index]) {
        if (0 == index) {
          this.setData({
            addrCurIndex: index,
          })
          return;
        } else {
          var parentId = that.data.addrDatas[index][0].parent_id
          var lastId = that.data.addrSelecteds[index - 1].id

          if (parentId == lastId) {
            this.setData({
              addrCurIndex: index,
            })
            return;
          }
        }
      }
    } catch (e) {}

    this.setData({
      showLoadAddr: true,
      addrCurIndex: index,
    })

    //加载地区列表
    var parentCode = "1"; //父及地区代码
    if (0 == index) {
      parentCode = "1";
    } else {
      parentCode = this.data.addrSelecteds[index - 1].id
    }

    httpUtil.PostRequest("select_area", {
      parentCode: parentCode
    }, {
      complete() {
        that.setData({
          showLoadAddr: false,
        })
      },
      success(res) {
        var addrDatas = that.data.addrDatas
        addrDatas[index] = res
        that.setData({
          addrDatas: addrDatas,
        })
      },
      fail(code, res) {}
    })
  },
  /**
   * 地址条目选择
   */
  addrItemClick(e) {
    var curTitleIndex = this.data.addrCurIndex //当前层级
    var addrSelecteds = this.data.addrSelecteds //

    var index = e.currentTarget.dataset.index
    var clickItem = this.data.addrDatas[curTitleIndex][index]

    addrSelecteds[curTitleIndex] = clickItem;

    if (3 == curTitleIndex) {
      //弹窗消失并返回
      this.setData({
        addrSelecteds: addrSelecteds,
        'addressInfo.areaName': clickItem.allname,
        'addressInfo.areaCode': clickItem.code,
        showAddrView: false,
      })
    } else {
      for (var i = curTitleIndex + 1; i < 4; i++) {
        addrSelecteds[i] = null
      }
      this.setData({
        addrSelecteds: addrSelecteds
      })
      this.addrChangeCurShow(curTitleIndex + 1)
    }
  },
  addrOutsideClick() {
    this.setData({
      showAddrView: false,
    })
  },

  /**
   * 新增收货地址接口
   */
  requestReplaceAddress(params) {
    uiUtil.showLoading("请稍候..")
    params.address = params.adress
    httpUtil.PostRequest("replace_take_adress", params, {
      success(res) {
        that.setData({
          'addressInfo.addressId': res.addressId
        })
        //更新上一页数据
        try {
          try {
            var pages = getCurrentPages()
            var lastPage = pages[pages.length - 2]

            if (that.data.isAddAddress) {
              lastPage.onResultAddAddress(that.data.addressInfo)
            } else {
              lastPage.onResultEditAddress(that.data.addressInfo)
            }
          } catch (e) {}
        } catch (e) {
          console.log(e)
        }
        wx.showToast({
          title: '保存收货地址成功',
          icon: "none",
          mask: true,
        })
        setTimeout(function() {
          wx.navigateBack({})
        }, 800)
      },
      fail(code, res) {
        uiUtil.showToast(res || "保存收货地址失败")
      },
      complete() {}
    })
  },

})